package com.lin.fengxiu.service;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.lin.fengxiu.core.enumeration.OrderStatus;
import com.lin.fengxiu.exception.http.ServerErrorException;
import com.lin.fengxiu.model.Order;
import com.lin.fengxiu.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName WxPaymentNotifyService
 * @Description TODO
 * @Author wushaopei
 * @Date 2021/4/12 6:37
 * @Version 1.0
 */
@Service
public class WxPaymentNotifyService {

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private WxPaymentService wxPaymentService;

    /**
     * @Description TODO 支付结果格式转换，并验证其中sign是否有效
     * @param data
     */
    public void processPayNotify(String data){
        Map<String, String> dataMap = new HashMap<>();
        try {
            // 读取微信支付结果，xml转为map
            dataMap = WXPayUtil.xmlToMap(data);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }

        // 获取微信支付配置参数
        WXPay wxPay = this.wxPaymentService.assmbleWxPayConfig();
        boolean valid;
        try {
            // 调用微信SDK方法——判断支付结果通知中的sign是否有效
            valid = wxPay.isPayResultNotifySignatureValid(dataMap);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServerErrorException(9999);
        }
        if(!valid){
            throw new ServerErrorException(9999);
        }

        String returnCode = dataMap.get("return_code");
        String orderNo = dataMap.get("out_trade_no");
        String resultCode = dataMap.get("result_code");

        if(!returnCode.equals("SUCCESS")){
            throw new ServerErrorException(9999);
        }
        if (orderNo == null){
            throw new ServerErrorException(9999);
        }
        if (!resultCode.equals("SUCCESS")){
            throw new ServerErrorException(9999);
        }

        this.deal(orderNo);
    }

    /**
     * @Description TODO 支付成功，更改订单状态为已支付。若有预扣除库存就不需要减库存，若无预扣除库存就减库存。
     * @param orderNo
     */
    private void deal(String orderNo) {
        // 查询订单
        Optional<Order> orderOptional = this.orderRepository.findFirstByOrderNo(orderNo);
        Order order = orderOptional.orElseThrow(()->new ServerErrorException(9999));

        // 更新订单状态
        int res = -1;
        if(order.getStatus().equals(OrderStatus.UNPAID.value())
                || order.getStatus().equals(OrderStatus.CANCELED.value())){
            this.orderRepository.updateStatusByOrderNo(orderNo, OrderStatus.PAID.value());
        }
    }
}
